package socket

import (
	"fmt"
	"github.com/gorilla/websocket"
	"runtime/debug"
	"time"
)

const (
	HEARTBEAT_TIME = 60 // 心跳时间，以秒为单位
)

type Client struct {
	Addr          string          // 客户端IP地址
	ID            string          // 用户ID
	Socket        *websocket.Conn // websocket连接
	HeartbeatTime uint64          // 上次心跳链接时间
	LoginTime     uint64          // 登录时间
	Message       chan *Message   // 消息
}

func NewClient(addr string, conn *websocket.Conn, id string) *Client {
	loginTime := uint64(time.Now().Unix())
	client := &Client{
		Addr:          addr,
		Socket:        conn,
		HeartbeatTime: loginTime,
		LoginTime:     loginTime,
		ID:            id,
		Message:       make(chan *Message, 100),
	}
	return client
}
func (client *Client) Read() {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("read stop", r)
		}
	}()
	for {
		_, message, err := client.Socket.ReadMessage()
		if err != nil {
			return
		}
		ProcessingData(client, message)
	}
}
func (client *Client) Write() {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("write stop", r)
		}
	}()
	for {
		select {
		case message := <-client.Message:
			if message.Type == Ping {
				fmt.Println(message.Type)
			} else if message.Type == Listen {
				fmt.Println(message.Type)
			}
		}
	}
}
func (client *Client) SendMsg(msg *Message) {
	fmt.Println(client)
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("SendMsg stop:", r, string(debug.Stack()))
		}
	}()
	client.Message <- msg
}
func (client *Client) Heart(time uint64) {
	client.HeartbeatTime = time
}
func (client *Client) Timeout() {}
